package com.xtool.livewallpaper.base

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.res.Configuration
import android.content.res.Resources
import com.ricky.enavigation.ENavigation
import com.tencent.mmkv.MMKV
import com.xtool.livewallpaper.WallpaperNotifyManager


/**
 *
 * @Author: Ricky
 * @Date: 2021/1/19
 */
open class MainApplication : Application() {
    companion object {
        lateinit var gContext: MainApplication
    }

    override fun attachBaseContext(base: Context?) {
        gContext = this
        super.attachBaseContext(base)
    }


    override fun onCreate() {
        super.onCreate()
        MMKV.initialize(this)
        ActivityStackManager.init(this)
        ENavigation.init(
            this,
            "app",
        )
        WallpaperNotifyManager.instance.connectWallpaperProcess {
            WallpaperNotifyManager.instance.pause()
        }
        ActivityStackManager.registerAppStatusChangedListener(object :
            ActivityStackManager.OnAppStatusChangedListener {
            //进入前台
            override fun onForeground(activity: Activity?) {
                WallpaperNotifyManager.instance.connectWallpaperProcess {
                    WallpaperNotifyManager.instance.pause()
                }
            }

            //进入后台
            override fun onBackground(activity: Activity?) {
                WallpaperNotifyManager.instance.connectWallpaperProcess {
                    WallpaperNotifyManager.instance.resume()
                }
            }
        })
    }


    override fun onConfigurationChanged(newConfig: Configuration) {
        if (newConfig.fontScale != 1f) resources
        super.onConfigurationChanged(newConfig)
    }

    override fun getResources(): Resources {
        val res: Resources = super.getResources()
        if (res.configuration.fontScale != 1f) {
            val newConfig = Configuration()
            newConfig.setToDefaults()
            res.updateConfiguration(newConfig, res.displayMetrics)
        }
        return res
    }
}